package com.example.java8.forkJoin;

import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * fork join
 *
 * @author qibao
 * @version v0.1 2020/12/17
 */
public class ForkJoinDemo extends RecursiveTask<Long> {

    private Long start;
    private Long end;
    private Long THRESHOLD = 500000L;

    public ForkJoinDemo(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        Long length = end - start;
        long sum = 0;
        //达到阈值开始计算
        if (length <= THRESHOLD) {
            for (long i = start; i <= end; ++i) {
                sum += i;
            }

            return sum;
        } else {
            Long middle = (start + end) / 2;

            ForkJoinDemo left = new ForkJoinDemo(start, middle);
            left.fork();//拆分子任务同时压入线程队列

            ForkJoinDemo right = new ForkJoinDemo(middle + 1, end);
            right.fork();

            return left.join() + right.join();
        }
    }

}
